#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
#define ERROR 0
typedef int ElementType;
struct SNode{
	ElementType *data;
	int top;
	int MaxSize;
};
typedef struct SNode *Stack;
Stack createStack(int MaxSize) {
	Stack S = (Stack)malloc(sizeof (struct SNode));
	S->data = (ElementType*) malloc(MaxSize * sizeof (ElementType));
	S->top = 0;
	S->MaxSize = MaxSize;
	return S;
	
}
Stack s1;
Stack s2;
bool isFull(Stack S) {
	return (S->top == S->MaxSize);
}
bool Push(Stack S,ElementType x) {
	if(isFull(S)) {
		Stack *tmp = (SNode**) realloc(S,sizeof (ElementType)*2);
		S = *tmp;
	}
	S->data[S->top] = x;
	S->top++;
	return true;
}
bool isEmpty(Stack S) {
	return (S->top == -1);
}
ElementType  Pop(Stack S) {
	if(isEmpty(S)) {
		printf("堆栈空");
		return ERROR;
	} else {
		int x = S->data[S->top - 1];
		S->top--;
		return x;
	}
}
ElementType  Peek(Stack S,int index) {
	if(isEmpty(S)) {
		printf("堆栈空");
		return ERROR;
	} else {
		int x = S->data[index];
		
		return x;
	}
}
void printStack(Stack S) {
	if(S ==NULL) {
		printf("未定义!\n");
		return;
	}
	printf("栈里的元素:\n");
	int x = S->top;
	printf("%d |___  ___| <-top\n",S->top );
	while ((S->top ) != 0) {
		printf("%d |___ %d ___| \n",S->top - 1,S->data[S->top - 1]);
		S->top --;
	}
	S->top = x;
	return;
}
void ConvertDec2Radix(Stack S,int dec,int radix) {
	do {
		Push(S,dec%radix);
		dec = dec / radix;
	} while (dec != 0);
	
}
void menu () {
	printf("==顺序栈的实现及其应用==\n");
	printf("      1.入栈      \n");
	printf("      2.出栈      \n");
	printf("      3.显示      \n");
	printf("      4.进制装换      \n");
	printf("      5.退出      \n");
	return;
}

void gamePush() {
	int input = 0;
	printf(">输入你要入栈的值: ");
	scanf("%d",&input);
	Push(s1,input);
	printf("入栈成功!\n");
	return;
}
void gamePop() {
	int x = Pop(s1);
	printf("出栈成功!,当前出栈的值: %d \n",x);
	return;
}
void printAll() {
	
	printf("请选择你要打印的栈(1,2): ");
	int x = 0;
	scanf("%d",&x);
	switch (x) {
	case 1:
		printStack(s1);
		break;
	case 2:
		printStack(s2);
		break;
	}
	return;
	
}
void gameConvertDec2Radix() {
	free(s2);
	s2 = createStack(5);
	int dec = 0;
	int radix = 0;
	printf("请输入要装换的十进制的数(0~1023): ");
	scanf("%d",&dec);
	printf("请输入要转换的进制(2-10): ");
	scanf("%d",&radix);
	ConvertDec2Radix(s2,dec,radix);
	int length = s2->top ;
	//printf("");
	char ch[length - 1];
	int size = length;
	for (int i = 0; i < length  ; i++) {
		ch[i] = Peek(s2,--size) + 48;
	}
	printf("> 十进制:( %d ) = (%s)2进制\n",dec,ch);
}
void test() {
	int input = 0;
	do {
		menu();
		printf("> 选择操作(1-5):");
		scanf("%d",&input);
		switch (input) {
		case 1:
			gamePush();
			break;
		case 2:
			gamePop();
			break;
		case 3:
			printAll();
			break;
		case 4:
			gameConvertDec2Radix();
			break;
		case 5:
			printf("退出成功!");
			return;
			
		default:
			break;
		}
	} while (1);
}
int main() {
	s1 = createStack(5);
	test();
	return 0;
}
